
var stompClient = null;
var meetingId;
var userId;
var username;
$(function () {
    $('#meeting-lock .btn-close').click(function () {
        closeMeetingLockDialog();
    });

    $('#meeting-lock #meeting-apply-button').click(function () {
        if(stompClient != null) {
            stompClient.send("/app/apply/" + meetingId, {}, username);
        } else {
            socketConnect(true);
        }

        $("#meeting-lock #meeting-lock-tips").html($MB.i18n('meeting.tips.join.applying'));
        $("#meeting-lock #meeting-apply-button").attr("disabled",true);
    });

    $('#meeting-lock').on('hide.bs.modal', function () {
        if(stompClient != null) {
            stompClient.disconnect();
            stompClient = null;
        }
    });
});

function showMeetingLock(mid, uid, name) {
    console.log("check lock meeting:" + mid + " " + uid + ",name=" + name);

    meetingId = mid;
    userId = uid;
    username = name;
    $('#meeting-lock').modal();

    socketConnect(false);
}

function socketConnect(sendCommand) {
    var header = {'userId': userId};

    var host = location.protocol + "//" + location.host + "/vc/";

    var socket = new SockJS(host);
    stompClient = Stomp.over(socket);
    stompClient.connect(
        header,
        function connectCallback(frame) {
            console.log('[ws]: on connected');
            stompClient.subscribe('/sub/apply/' + meetingId + "/" + userId, function (response) {
                if(response.body != "false") {
                    closeMeetingLockDialog();
                    window.open(response.body, '_blank').location;
                } else {

                }
            });

            if(sendCommand) {
                stompClient.send("/app/apply/" + meetingId, {}, username);
            };
        },
        function errorCallBack(error) {
            console.log('[ws]: on connect error');
            stompClient = null;
        }
    );
}


function closeMeetingLockDialog() {
    $("#meeting-lock #meeting-apply-button").removeAttr("disabled");
    $MB.closeModal('meeting-lock');
}